#include "RenderThread.h"
#include <mimalloc.h>

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // !WIN32_LEAN_AND_MEAN
#include <Windows.h>

struct 
{
	d3d12::Command* cmd;
	d3d12::Surface surface;
	bool render_life;
	HANDLE thread_handle;
}gb{};

DWORD render_main(LPVOID par)
{
	while (gb.render_life)
	{
		auto list = gb.cmd->Begin();
		gb.cmd->SurfacePresentBegin(gb.surface, list);
		gb.cmd->SurfacePresentEnd(gb.surface);
		gb.cmd->End();
	}
	return 0;
}

void BeginRenderThread(HWND winid)
{
	auto cmd_ptr = mi_malloc(sizeof d3d12::Command);
	gb.cmd = new(cmd_ptr)d3d12::Command{};

	gb.cmd->SurfaceCreate(gb.surface, winid);

	gb.render_life = true;
	gb.thread_handle = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)render_main, nullptr, 0, nullptr);
}

void EndRenderThread()
{
	gb.cmd->SurfaceDestory(gb.surface);
	gb.cmd->~Command();
	mi_free(gb.cmd);
	gb.cmd = nullptr;
}
